<template>
  <div class="inventory-movement-report">
    <!-- 搜索过滤区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="商品">
          <el-select 
            v-model="filterForm.productId" 
            placeholder="选择商品" 
            clearable
            filterable
            :remote="true"
            :remote-method="searchProducts"
            :loading="productsLoading"
          >
            <el-option 
              v-for="product in products" 
              :key="product.id" 
              :label="product.name" 
              :value="product.id" 
            >
              <div class="product-option">
                <span>{{ product.name }}</span>
                <span class="product-option-desc">{{ product.sku }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="filterForm.warehouseId" placeholder="选择仓库" clearable>
            <el-option v-for="warehouse in warehouses" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="变动类型">
          <el-select v-model="filterForm.movementType" placeholder="选择类型" clearable>
            <el-option v-for="(name, value) in movementTypes" :key="value" :label="name" :value="Number(value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 库存流水表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%;"
      v-loading="loading"
    >
      <el-table-column label="商品" min-width="200">
        <template #default="scope">
          <div>
            <div>{{ scope.row.product ? scope.row.product.name : '' }}</div>
            <div class="text-muted">{{ scope.row.product ? scope.row.product.sku : '' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="仓库" width="120">
        <template #default="scope">
          {{ scope.row.warehouse ? scope.row.warehouse.name : '' }}
        </template>
      </el-table-column>
      <el-table-column label="变动类型" width="100">
        <template #default="scope">
          <el-tag :type="getMovementTypeTag(scope.row.movementType)">
            {{ getMovementTypeText(scope.row.movementType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="变动数量" width="120">
        <template #default="scope">
          <span :class="getQuantityClass(scope.row.movementType)">
            {{ getQuantityPrefix(scope.row.movementType) }}{{ scope.row.quantity }} {{ scope.row.product ? scope.row.product.stockUnit : '' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="变动前数量" width="120">
        <template #default="scope">
          {{ scope.row.beforeQuantity }} {{ scope.row.product ? scope.row.product.stockUnit : '' }}
        </template>
      </el-table-column>
      <el-table-column label="变动后数量" width="120">
        <template #default="scope">
          {{ scope.row.afterQuantity }} {{ scope.row.product ? scope.row.product.stockUnit : '' }}
        </template>
      </el-table-column>
      <el-table-column label="操作人" width="120">
        <template #default="scope">
          {{ scope.row.operator ? scope.row.operator.name : '' }}
        </template>
      </el-table-column>
      <el-table-column label="变动时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" min-width="200" show-overflow-tooltip />
    </el-table>
    
    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch, inject } from 'vue';
import { getInventoryMovementReport } from '@/api/inventory';
import { getAllWarehouses } from '@/api/inventory';
import { searchProduct } from '@/api/product';
import { formatDateTime } from '@/utils/format';

export default {
  name: 'InventoryMovementReport',
  emits: ['loading-change'],
  setup(props, { emit }) {
    const loading = inject('loading', ref(false));
    
    // 表格数据
    const tableData = ref([]);
    const total = ref(0);
    const page = ref(1);
    const pageSize = ref(20);
    
    // 基础数据
    const warehouses = ref([]);
    const products = ref([]);
    const productsLoading = ref(false);
    
    // 日期范围
    const dateRange = ref([]);
    
    // 过滤条件
    const filterForm = reactive({
      productId: null,
      warehouseId: null,
      movementType: null,
      startDate: null,
      endDate: null
    });
    
    // 变动类型映射
    const movementTypes = {
      1: '入库',
      2: '出库',
      3: '盘盈',
      4: '盘亏',
      5: '调整'
    };
    
    // 日期快捷选项
    const dateShortcuts = [
      {
        text: '最近一周',
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          return [start, end];
        }
      },
      {
        text: '最近一个月',
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          return [start, end];
        }
      },
      {
        text: '最近三个月',
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          return [start, end];
        }
      }
    ];
    
    // 监听日期范围变化
    watch(dateRange, (newVal) => {
      if (newVal && newVal.length === 2) {
        filterForm.startDate = newVal[0];
        filterForm.endDate = newVal[1];
      } else {
        filterForm.startDate = null;
        filterForm.endDate = null;
      }
    });
    
    // 获取变动类型标签颜色
    const getMovementTypeTag = (type) => {
      const map = {
        1: 'success', // 入库
        2: 'danger',  // 出库
        3: 'primary', // 盘盈
        4: 'warning', // 盘亏
        5: 'info'     // 调整
      };
      return map[type] || '';
    };
    
    // 获取变动类型文本
    const getMovementTypeText = (type) => {
      return movementTypes[type] || '未知';
    };
    
    // 获取数量变动前缀
    const getQuantityPrefix = (type) => {
      if (type === 1 || type === 3) {
        return '+';
      } else if (type === 2 || type === 4) {
        return '-';
      }
      return '';
    };
    
    // 获取数量样式类
    const getQuantityClass = (type) => {
      if (type === 1 || type === 3) {
        return 'quantity-increase';
      } else if (type === 2 || type === 4) {
        return 'quantity-decrease';
      }
      return '';
    };
    
    // 获取库存流水报表数据
    const fetchData = async () => {
      emit('loading-change', true);
      try {
        // 构建查询参数
        const params = {
          ...filterForm,
          page: page.value,
          pageSize: pageSize.value
        };
        
        const response = await getInventoryMovementReport(params);
        tableData.value = response.data.items || [];
        total.value = response.data.total || 0;
      } catch (error) {
        console.error('获取库存流水报表失败:', error);
      } finally {
        emit('loading-change', false);
      }
    };
    
    // 加载基础数据
    const loadBaseData = async () => {
      try {
        const response = await getAllWarehouses();
        warehouses.value = response.data || [];
      } catch (error) {
        console.error('加载仓库数据失败:', error);
      }
    };
    
    // 搜索商品
    const searchProducts = async (query) => {
      if (query.length < 2) return;
      
      productsLoading.value = true;
      try {
        const response = await searchProduct({ keyword: query, pageSize: 20 });
        products.value = response.data.items || [];
      } catch (error) {
        console.error('搜索商品失败:', error);
      } finally {
        productsLoading.value = false;
      }
    };
    
    // 分页大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val;
      fetchData();
    };
    
    // 页码变化
    const handleCurrentChange = (val) => {
      page.value = val;
      fetchData();
    };
    
    // 查询按钮事件处理
    const handleSearch = () => {
      page.value = 1;
      fetchData();
    };
    
    // 重置按钮事件处理
    const handleReset = () => {
      Object.keys(filterForm).forEach(key => {
        filterForm[key] = null;
      });
      dateRange.value = [];
      page.value = 1;
      fetchData();
    };
    
    // 获取导出参数
    const getExportParams = () => {
      return { ...filterForm };
    };
    
    onMounted(() => {
      loadBaseData();
      fetchData();
    });
    
    return {
      loading,
      tableData,
      total,
      page,
      pageSize,
      warehouses,
      products,
      productsLoading,
      filterForm,
      dateRange,
      movementTypes,
      dateShortcuts,
      getMovementTypeTag,
      getMovementTypeText,
      getQuantityPrefix,
      getQuantityClass,
      fetchData,
      searchProducts,
      handleSizeChange,
      handleCurrentChange,
      handleSearch,
      handleReset,
      getExportParams,
      formatDateTime
    };
  }
};
</script>

<style scoped>
.inventory-movement-report {
  margin-top: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.text-muted {
  font-size: 12px;
  color: #909399;
}

.product-option {
  display: flex;
  flex-direction: column;
}

.product-option-desc {
  font-size: 12px;
  color: #909399;
}

.quantity-increase {
  color: #67C23A;
  font-weight: bold;
}

.quantity-decrease {
  color: #F56C6C;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media print {
  .filter-container,
  .pagination-container {
    display: none !important;
  }
}
</style>